package com.todo.admin.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.Producer;
import com.todo.admin.service.api.AdminStaffServiceApi;
import com.todo.admin.service.api.request.QueryStaffDetailByUserNameReq;
import com.todo.admin.service.api.request.QueryUserInfoByIdReq;
import com.todo.admin.service.api.request.RecordLoginInfoReq;
import com.todo.admin.service.api.response.CaptchaResp;
import com.todo.admin.service.api.response.QueryStaffDetailByUserNameResp;
import com.todo.admin.service.api.response.UserDetailResp;
import com.todo.admin.common.base.consts.Constants;
import com.todo.admin.common.cache.GuavaCacheService;
import com.todo.admin.common.exception.ApiException;
import com.todo.admin.common.exception.error.ErrorCode;
import com.todo.admin.config.TodoStrategyConfig;
import com.todo.admin.entity.enums.common.ConfigKeyEnum;
import com.todo.admin.entity.enums.common.UserStatusEnum;
import com.todo.admin.service.login.LoginService;
import com.todo.admin.system.user.UserApplicationService;
import com.todo.admin.system.user.db.SysUserEntity;
import com.todo.admin.system.user.db.SysUserService;
import com.todo.admin.system.user.dto.UserDTO;
import com.todo.admin.common.base.RoleInfo;
import com.todo.admin.common.base.SystemLoginUser;
import com.todo.common.common.entity.response.BizResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.Objects;

/**
 * @author azhebuxing
 * @date 2025/2/20 00:58
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/api/system/staff")
@RequiredArgsConstructor
@Tag(name = "系统用户对内服务api", description = "系统用户对内服务api")
public class AdminStaffApiController implements AdminStaffServiceApi {

    private final SysUserService userService;

    private final LoginService loginService;

    private final GuavaCacheService guavaCache;

    private final UserApplicationService userApplicationService;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;


    @Override
    @Operation(summary = "根据员工名字获取详情信息", description = "根据员工名字获取详情信息")
    @PostMapping("/queryStaffDetailByUserName")
    public BizResponse<QueryStaffDetailByUserNameResp> queryStaffDetailByUserName(@RequestBody QueryStaffDetailByUserNameReq req) {
        if (req == null || req.getUsername() == null) {
            return BizResponse.success();
        }
        String username = req.getUsername();
        SysUserEntity userEntity = userService.getUserByUserName(username);
        if (userEntity == null) {
            log.info("AdminStaffController 登录用户：{} 不存在.", username);
            throw new ApiException(ErrorCode.Business.USER_NON_EXIST, username);
        }
        if (!Objects.equals(UserStatusEnum.NORMAL.getValue(), userEntity.getStatus())) {
            log.info("AdminStaffController 登录用户：{} 已被停用.", username);
            throw new ApiException(ErrorCode.Business.USER_IS_DISABLE, username);
        }

        RoleInfo roleInfo = userApplicationService.getRoleInfo(userEntity.getRoleId(), userEntity.getIsAdmin());

        SystemLoginUser loginUser = new SystemLoginUser(userEntity.getUserId(), userEntity.getIsAdmin(), userEntity.getUsername(),
                userEntity.getPassword(), roleInfo, userEntity.getDeptId());
        loginUser.fillLoginInfo();
        QueryStaffDetailByUserNameResp resp = new QueryStaffDetailByUserNameResp();
        resp.setAdmin(userEntity.getIsAdmin());
        resp.setDeptId(userEntity.getDeptId());
        resp.setUserId(userEntity.getUserId());
        resp.setUsername(userEntity.getUsername());
        resp.setPassword(userEntity.getPassword());
        resp.setRoleInfo(roleInfo);
        resp.getLoginInfo().setLoginTime(loginUser.getLoginInfo().getLoginTime());
        resp.getLoginInfo().setIpAddress(loginUser.getLoginInfo().getIpAddress());
        resp.getLoginInfo().setLocation(loginUser.getLoginInfo().getLocation());
        resp.getLoginInfo().setBrowser(loginUser.getLoginInfo().getBrowser());
        resp.getLoginInfo().setOperationSystem(loginUser.getLoginInfo().getOperationSystem());
        resp.setAutoRefreshCacheTime(loginUser.getAutoRefreshCacheTime());
        resp.setCachedKey(loginUser.getCachedKey());
        return BizResponse.success(resp);
    }

    @Override
    @Operation(summary = "根据用户Id查询用户信息详情")
    @PostMapping("/queryUserInfoById")
    public BizResponse<UserDetailResp> queryUserInfoById(@RequestBody QueryUserInfoByIdReq req) {
        UserDTO userDTO = userApplicationService.getUserDTO(req.getUserId());
        UserDetailResp resp = new UserDetailResp();
        BeanUtil.copyProperties(userDTO, resp);
        return BizResponse.success(resp);
    }

    @Override
    @Operation(summary = "记录用户登录信息")
    @PostMapping("/recordLoginInfo")
    public BizResponse<Boolean> recordLoginInfo(RecordLoginInfoReq req) {
        if (req == null || req.getUserId() == null || req.getUsername() == null) {
            return BizResponse.success();
        }
        loginService.recordLoginInfo(req.getUsername(), req.getUserId());
        return BizResponse.success();
    }

    /**
     * 生成验证码
     */
    @Override
    @Operation(summary = "验证码")
    @GetMapping("/captchaImage")
    public BizResponse<CaptchaResp> getCaptchaImg() {
        CaptchaResp captchaResp = new CaptchaResp();

        boolean isCaptchaOn = isCaptchaOn();
        captchaResp.setIsCaptchaOn(isCaptchaOn);

        if (isCaptchaOn) {
            String expression;
            String answer = null;
            BufferedImage image = null;

            // 生成验证码
            String captchaType = TodoStrategyConfig.getCaptchaType();
            if (Constants.Captcha.MATH_TYPE.equals(captchaType)) {
                String capText = captchaProducerMath.createText();
                String[] expressionAndAnswer = capText.split("@");
                expression = expressionAndAnswer[0];
                answer = expressionAndAnswer[1];
                image = captchaProducerMath.createImage(expression);
            }

            if (Constants.Captcha.CHAR_TYPE.equals(captchaType)) {
                expression = answer = captchaProducer.createText();
                image = captchaProducer.createImage(expression);
            }

            if (image == null) {
                throw new ApiException(ErrorCode.Internal.LOGIN_CAPTCHA_GENERATE_FAIL);
            }

            // 保存验证码信息
            String imgKey = IdUtil.simpleUUID();
            captchaResp.setAnswer(answer);
            // 转换流信息写出
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            ImgUtil.writeJpg(image, os);

            captchaResp.setCaptchaCodeKey(imgKey);
            captchaResp.setCaptchaCodeImg(Base64.encode(os.toByteArray()));

        }

        return BizResponse.success(captchaResp);
    }

    private boolean isCaptchaOn() {
        return Convert.toBool(guavaCache.configCache.get(ConfigKeyEnum.CAPTCHA.getValue()));
    }



}
